package service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;

import beans.Customer;
import beans.Info;
import beans.Task;
import dao.DAO;

public class TaskService {
	public static final int PERPAGE = 5; // 分页每页显示条数
	private DAO<Task> dao;

	public TaskService() {
		dao = new DAO<Task>(Task.class);
	}

	// 接单
	public void orderTask(String id, int customerId) {
		dao.getSession().beginTransaction();
		Task task = (Task) dao.getSession().get(Task.class, Integer.parseInt(id));
		task.setOrderCustomer((Customer) dao.getSession().get(Customer.class, customerId));
		task.setStatus("已接单");
		dao.getSession().update(task);
		dao.getSession().getTransaction().commit();
	}
	/**
	 * 分页获取所有信息
	 * 
	 * @param page
	 * @return
	 */
	public Info<Task> getTask(String page) {
		int startP = (Integer.parseInt(page) - 1) * PERPAGE; // 分页开始条数
		Map<Long, List<Task>> map = dao.getAll(startP, PERPAGE);
		Info<Task> info = new Info<>();
		info.count = map.keySet().iterator().next();
		info.list = map.values().iterator().next();
		return info;
	}
	/**
	 * 分页获取客户发布的信息
	 * 
	 * @param page
	 * @return
	 */
	public Info<Task> getTaskByCustomer(String page, int id) {
		int startP = (Integer.parseInt(page) - 1) * PERPAGE; // 分页开始条数
		String hql = "from Task where customer.id=" + id;
		Map<Long, List<Task>> map = dao.getFromHQL(hql, startP, PERPAGE);
		Info<Task> info = new Info<>();
		info.count = map.keySet().iterator().next();
		info.list = map.values().iterator().next();
		return info;
	}

	/**
	 * 根据id获取信息
	 * 
	 * @param id
	 * @return
	 */
	public Info<Task> getTaskById(String id) {
		Info<Task> info = new Info<>();
		info.count = 1L;
		info.list = new ArrayList<>();
		info.list.add(dao.getById(Integer.parseInt(id)));
		return info;
	}

	/**
	 * 添加信息
	 * 
	 * @param task
	 */
	public void addTask(Task task) {
		dao.add(task);
	}

	/**
	 * 删除信息
	 * 
	 * @param id
	 */
	public void delTask(String id) {
		dao.delById(Integer.parseInt(id));
	}

	/**
	 * 根据id修改信息
	 * 
	 * @param tid
	 * @param name
	 * @param tel
	 * @param message
	 * @param money
	 * @param address
	 */
	public void alterTask(String tid, String name, String tel, String message, String money, String address) {
		String sql = "update task t, customer c set c.username='" + name + "', c.tel='" + tel + "', t.message='"
				+ message + "', t.money=" + money + ", t.address='" + address + "' where t.tid=" + tid
				+ " and t.customer=c.uid";
		dao.updateSQL(sql);
	}

	public String orderedTask(int customerId, String page) {
		String hql = "from Task where orderCustomer.id=" + customerId;
		if (page == null || page.equals("")) {
			page = "1";
		}
		Map<Long, List<Task>> tasks = dao.getFromHQL(hql, (Integer.parseInt(page) - 1) * PERPAGE, PERPAGE);
		return new Gson().toJson(tasks.values().iterator().next());
	}
}
